<?php
class Model implements ArrayAccess, Iterator {
	
	protected $_isSaved = false;
	protected $_updatePK = true;
	
	protected $_properties = array();
	
	public function __construct(array $properties = array()) 
	{
		$this->setProperties($properties);
	}
	
	public function setProperties(array $properties) 
	{
		$this->_properties = $properties;	
	}
	
	public function getProperties()
	{
		return $this->_properties;
	}
	
	public function __isset($name) 
	{
		return isset($this->_properties[$name]);
	}
	
	public function __unset($name)
	{
		unset($this->_properties[$name]);
	}
	
	public function __get($name)
	{
		return isset($this->_properties[$name]) ? $this->_properties[$name] : null;
	}
	
	public function __set($name, $value)
	{
		$this->_properties[$name] = $value;
	}
	
	/** ArrayAccess **/
	
	public function offsetExists($offset) 
	{
		return isset($this->_properties[$offset]);
	}

	public function offsetGet($offset) 
	{
		return isset($this->_properties[$offset]) ? $this->_properties[$offset] : null;
	}

	public function offsetSet($offset, $value) 
	{
		$this->_properties[$offset] = $value;
	}

	public function offsetUnset($offset) 
	{
		unset($this->_properties[$offset]);
	}
	
	/** Iterator **/
	public function current() 
	{
		return current($this->_properties);
	}

	public function next() 
	{
		return next($this->_properties);
	}

	public function key() 
	{
		return key($this->_properties);
	}

	public function valid() 
	{
		return isset($this->_properties[$this->key()]);
	}

	public function rewind() 
	{
		return rewind($this->_properties);
	}
	
	public function getPK()
	{
		$manager = get_called_class() . 'Manager';
		return $manager::PK_NAME;
	}
	
	public function getPKValue()
	{
		return $this[$this->getPK()];
	}
	
	public function setPKValue($value)
	{
		if ($this->_updatePK)
			$this[$this->getPK()] = $value;
	}
	
	public function hasPKValue()
	{
		return !! $this->getPKValue();
	}
	
	public function isSaved()
	{
		return $this->_isSaved;
	}
	
	public function setSaved($isSaved = true)
	{
		$this->_isSaved = $isSaved;
	}
	
}